package community.controller;

import community.dto.AccessTokenDto;
import community.dto.GithubUser;
import community.mapper.UserMapper;
import community.model.User;
import community.provider.GithubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author : 赵静超
 * @version V1.0
 * @Project: community
 * @Package community.controller
 * @Description: TODO
 * @date Date : 2019/8/31 22:22
 */


@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    //@Value注解里的值映射源为配置文件里的属性
    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.url}")
    private String redirectUrl;

    //@Autowired会使spring将userMapper类自动装配进来
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/redirect")
    public String redirect(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest servletRequest,  //session是在 HttpServletRequest 中拿到的
                           HttpServletResponse servletResponse) {    //cookies是在HttpServletResponse中拿到的
        AccessTokenDto accessTokenDto = new AccessTokenDto();
        accessTokenDto.setClient_id(clientId);
        accessTokenDto.setClient_secret(clientSecret);
        accessTokenDto.setCode(code);
        accessTokenDto.setRedirect_uri(redirectUrl);
        accessTokenDto.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDto);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        //判断是够存在user信息
        if(githubUser!=null){
            //登录成功，写session和cookies，使浏览器保持登录状态
            User user = new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setAccountId(String.valueOf(githubUser.getId()));      //将Long型id强转为String类型
            user.setName(githubUser.getName());
            user.setGmtCreate(System.currentTimeMillis());      //当前时间
            user.setGmtModify(user.getGmtCreate());
            userMapper.insert(user);
            servletResponse.addCookie(new Cookie("token",token));  //将token放到cookies里面
            servletRequest.getSession().setAttribute("user",githubUser);  //写入session对象
            return "redirect:/";  //写入session成功后重新跳转到index初试页面，为初始url
        }else{
            //登录失败，重新登录
            return "redirect:/";
        }
    }
}